<?php
/**
 * @link https://www.kancloud.cn/cleverstone/ymb2
 * @copyright Copyright (c) 2020 Yii Manager Software LLC
 */

namespace builder\helper;

/**
 * 数字
 * @author cleverstone
 * @since ym2.0
 */
class Num
{
    /**
     * 随机数字
     * @param int $len 最小长度1，最大长度10
     * @return int
     */
    public static function random($len = 6)
    {
        $minLength = 1;
        // 最大长度不能超出10位数,否则PHP引擎会自动转换为浮点型
        $maxLength = 10;

        $defaultLength = 6;
        if ($len < $minLength || $len > $maxLength) {
            $len = $defaultLength;
        }

        if ($len <= 1) {
            $min = 0;
        } else {
            $min = pow(10, $len - 1);
        }

        if ($len >= 10) {
            $max = 2147483647;
        } else {
            $max = pow(10, $len) - 1;
        }

        return mt_rand($min, $max);
    }

    /**
     * 随机单号（不含前缀18位）
     * @param string $prefix 前缀
     * @return string
     */
    public static function order($prefix = '')
    {
        $prefix = (string)$prefix;
        $randomNo = sprintf('%03d', mt_rand(0, 999));

        // the total length = ? + 12 + 3 + 3 = ? + 18
        return $prefix . date('ymdHis') . substr(microtime(), 2, 3) . $randomNo;
    }
}